package com.jakewharton.rxbinding4.component;

import static com.jakewharton.rxbinding4.internal.Preconditions.checkMainThread;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.openharmony.MainThreadDisposable;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;

final class ListContainerItemSelectedObservable extends Observable<ListContainerItemEvent> {
    private final ListContainer view;

    ListContainerItemSelectedObservable(ListContainer view) {
        this.view = view;
    }

    @Override
    protected void subscribeActual(Observer<? super ListContainerItemEvent> observer) {
        if (!checkMainThread(observer)) {
            return;
        }
        Listener listener = new Listener(view, observer);
        observer.onSubscribe(listener);
        view.setItemSelectedListener(listener);
    }

    static final class Listener extends MainThreadDisposable implements ListContainer.ItemSelectedListener {
        private final ListContainer view;
        private final Observer<? super ListContainerItemEvent> observer;

        Listener(ListContainer view, Observer<? super ListContainerItemEvent> observer) {
            this.view = view;
            this.observer = observer;
        }

        @Override
        protected void onDispose() {
            view.setItemSelectedListener(null);
        }

        @Override
        public void onItemSelected(ListContainer parent, Component component, int position, long id) {
            if (!isDisposed()) {
                observer.onNext(ListContainerItemEvent.create(parent, component, position, id));
            }
        }
    }
}
